package com.GreenIce.android.UI;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.GreenIce.android.GreenIceActivity;
import com.GreenIce.android.R;
import com.GreenIce.android.datastructure.ConfigData;
import com.GreenIce.android.datastructure.ConfigData.WorldInfo;
import com.GreenIce.android.datastructure.ConfigHandler;
import com.GreenIce.android.datastructure.GameLevel;
import com.GreenIce.android.util.DirectionIdentifier;
import com.GreenIce.android.util.DistanceSensor;
import com.GreenIce.android.util.HeadSetManager;
import com.GreenIce.android.util.SoundEffectManager;

public class UImanager {
	static UImanager uimanager;	
	public static UImanager getInstance() {
		if (uimanager== null)
			uimanager = new UImanager(GreenIceActivity.getActivity());
		return uimanager;
	}
	
	private Activity activity;
	private UImanager(Activity activity){
		this.activity = activity; 
//		KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
//		kl = km.newKeyguardLock("setGamePlayingView");
	}
	/**
	 * 主界面
	 */
	public void setMainView(){
		DistanceSensor.setHandler(null);
		DistanceSensor.disable();
		HeadSetManager.disable();
		activity.setContentView(R.layout.main);
		ImageButton bt = (ImageButton) activity.findViewById(R.id.main_start);
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setChooseWorldView();
			}
		});
		bt = (ImageButton) activity.findViewById(R.id.main_about);
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(activity)
				.setTitle(R.string.about)
				.setMessage(R.string.about_info)
				.setPositiveButton(R.string.yes, null)
				.show();
			}
		});
		bt = (ImageButton) activity.findViewById(R.id.main_help);
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater li = activity.getLayoutInflater();
				View hv = li.inflate(R.layout.help, null);
				new AlertDialog.Builder(activity)
				.setTitle(R.string.help)
				.setView(hv)
				.setPositiveButton(R.string.yes, null)
				.show();
			}
		});
		ConfigData.getInstance().status = 0;
		ConfigData.getInstance().curWorld = -1;
		ConfigData.getInstance().curLevel = -1;
	}
	/**
	 * 世界选择界面
	 */
	public void setChooseWorldView(){
		DistanceSensor.setHandler(null);
		DistanceSensor.disable();
		HeadSetManager.disable();
		activity.setContentView(R.layout.chooseworld);
		
		final ImgGallery world = (ImgGallery)activity.findViewById(R.id.world_gallery);
		final SeekBar worldBar = (SeekBar)activity.findViewById(R.id.world_seek);
		worldBar.setMax(ConfigData.getInstance().worldNum-1);
		WorldAdapter worldAdapter = new WorldAdapter(activity, ConfigData.getInstance().worldNum);
		world.setAdapter(worldAdapter);
		world.setUnselectedAlpha(1.0f);
		world.setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int action = event.getAction();
				switch (action) {
			    case MotionEvent.ACTION_DOWN:
			    	return false;
			    case MotionEvent.ACTION_UP:
			    	return false;
			    case MotionEvent.ACTION_MOVE:
			    	return false;
				}
				return true;
			}
		});
		world.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				int select = world.getSelectedItemPosition();
				if(select == arg2){
					int starNum = ConfigData.getInstance().starNum;
					WorldInfo aWorld = ConfigData.getInstance().worldInfo.get(arg2);
					if(starNum >= aWorld.lockStar){
						setChooseLevelView(arg2);
					}
					else{
						Resources r = activity.getResources();
						String res = r.getString(R.string.need)
									+ " " + aWorld.lockStar + " "
									+ r.getString(R.string.star);
						Toast.makeText(activity, res, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		world.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				worldBar.setProgress(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});	
		worldBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				int choose = seekBar.getProgress();
				world.setSelection(choose);
			}
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				int choose = seekBar.getProgress();
				world.setSelection(choose);
			}
		});
		
		TextView text = (TextView)activity.findViewById(R.id.world_star);
		Resources r = activity.getResources();
		String res = r.getString(R.string.starsum)
					+ ConfigData.getInstance().starNum
					+ "/"
					+ ConfigData.getInstance().starSum;
		text.setText(res);
		
		ConfigData.getInstance().status = 1;
		ConfigData.getInstance().curWorld = -1;
		ConfigData.getInstance().curLevel = -1;
	}
	/**
	 * 关卡选择界面
	 * @param wid 所选世界的id
	 */
	public void setChooseLevelView(final int wid){
		DistanceSensor.setHandler(null);
		DistanceSensor.disable();
		HeadSetManager.disable();
		activity.setContentView(R.layout.chooselevel);

		final WorldInfo aWorld = ConfigData.getInstance().worldInfo.get(wid);
		LevelAdapter levelAdapter = new LevelAdapter(activity, aWorld.levelNum, wid);
		GridView level = (GridView)activity.findViewById(R.id.level_view);
		level.setAdapter(levelAdapter);
		level.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(arg2 <= aWorld.playNum){
					int levelNumber = 0;
					for(int i=0; i<wid; i++){
						WorldInfo eachWorld = ConfigData.getInstance().worldInfo.get(i);
						levelNumber += eachWorld.levelNum;
					}
					levelNumber += arg2;
					//levelNumber++;
					setGameStartView(levelNumber);
				}
			}
		});
		
		TextView text = (TextView) activity.findViewById(R.id.inner_star);
		Resources r = activity.getResources();
		String res = r.getString(R.string.starsum)
					+ ConfigData.getInstance().worldInfo.get(wid).starSumW
					+ "/"
					+ ConfigData.getInstance().worldInfo.get(wid).levelNum*3;
		text.setText(res);
		
		ConfigData.getInstance().status = 2;
		ConfigData.getInstance().curWorld = wid;
	}
	/**
	 * 游戏开始界面
	 * @param level,所选关卡号
	 */
	public void setGameStartView(int level){
		DistanceSensor.setHandler(null);
		DistanceSensor.disable();
		HeadSetManager.disable();
		activity.setContentView(R.layout.game_start);
		final GameLevel gamelevel = new GameLevel(level);
		SoundEffectManager.releaseMediaplayer();
		ImageButton bt = (ImageButton) activity.findViewById(R.id.ready);
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DirectionIdentifier.setRelativeDirection();
				if(!HeadSetManager.getInstance().isPlug()){
					Dialog dialog = new AlertDialog.Builder(activity)
					  .setTitle(R.string.warning)
					  .setMessage(R.string.ear)
					  .setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton){
						}
					  })
					  .create();
					dialog.show();
				}
				else{
					setGamePlayingView(gamelevel);
				}
			}
		});
		TextView tv = (TextView) activity.findViewById(R.id.guid);
		tv.setText("Level:"+(level+1));
		ConfigData.getInstance().status = 3;
		ConfigData.getInstance().curWorld = level / 9;
		ConfigData.getInstance().curLevel = level;
	}
	/**
	 * 游戏进行界面
	 * @param gl 正在进行的关卡参数
	 */
	public void setGamePlayingView(GameLevel gl){
		final PlayingView masterPlayingView = new PlayingView(activity);
		playingView = masterPlayingView.show(gl);
		
		DistanceSensor.setHandler(new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				if (msg.what == 0){
//					kl.disableKeyguard();
					GreenIceActivity.getActivity().setContentView(R.layout.empty);
				} else {
//					kl.reenableKeyguard();
					GreenIceActivity.getActivity().setContentView(playingView);
				}
				return true;
			}
		}));
		DistanceSensor.enable();
		HeadSetManager.enable();
		HeadSetManager.setHandler(new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				// TODO Auto-generated method stub
				GreenIceActivity.getActivity().setContentView(playingView);
				masterPlayingView.pause();
				masterPlayingView.showDlg();
				Dialog dialog = new AlertDialog.Builder(activity)
				  .setTitle(R.string.warning)
				  .setMessage(R.string.ear)
				  .setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton){
					}
				  })
				  .create();
				dialog.show();
				return true;
			}
		}));
		ConfigData.getInstance().status = 4;
		ConfigData.getInstance().curLevel = gl.level;
	}
	View playingView;
//	KeyguardManager.KeyguardLock kl;
	/**
	 * 游戏结束界面
	 * @param score 得分, 0表示失败
	 * @param star 星星数, 0-3,
	 */
	public void setGameOverView(int score,int star){
		if (star == 0)
			SoundEffectManager.playFail();
		else if (star == 3)
			SoundEffectManager.playBigClear();
		else 
			SoundEffectManager.playClear();
		
		DistanceSensor.setHandler(null);
		DistanceSensor.disable();
		HeadSetManager.disable();
		Log.v("!!!"+score, "!!!"+star);
		activity.setContentView(R.layout.game_over);
		
		int wid = ConfigData.getInstance().curWorld;
		Log.v("wid", wid+"");
		int levelnumber = ConfigData.getInstance().curLevel;
		WorldInfo aWorld = ConfigData.getInstance().worldInfo.get(wid);
		for(int i=0; i<wid; i++){
			levelnumber -= ConfigData.getInstance().worldInfo.get(i).levelNum;
		}
		//levelnumber--;
		if(levelnumber == aWorld.playNum && aWorld.playNum<aWorld.levelNum && star!=0){
			aWorld.playNum++;
		}
		int pastStar = aWorld.eachLevel[levelnumber];
		if(star > pastStar){
			aWorld.starSumW += (star - pastStar);
			aWorld.eachLevel[levelnumber] = star;
			ConfigData.getInstance().starNum += (star - pastStar);
		}
		TextView gameInfo = (TextView) activity.findViewById(R.id.game_over_info);
		RatingBar starBar = (RatingBar) activity.findViewById(R.id.star_num);
		TextView gameScore = (TextView) activity.findViewById(R.id.game_over_score);
		ImageButton retry = (ImageButton) activity.findViewById(R.id.retry);
		ImageButton next = (ImageButton) activity.findViewById(R.id.nextlevel);
		
		if(star == 0){
			gameInfo.setText(R.string.falied);
			next.setVisibility(View.GONE);
		}
		else if(star == 1){
			gameInfo.setText(R.string.soso);
		}
		else if(star == 2){
			gameInfo.setText(R.string.good);
		}
		else if(star == 3){
			gameInfo.setText(R.string.perfect);
		}
		Resources r = activity.getResources();
		String res = r.getString(R.string.score)+score;
		gameScore.setText(res);
		starBar.setIsIndicator(true);
		starBar.setNumStars(3);
		starBar.setStepSize(1.0f);
		starBar.setRating(star);
		retry.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setGameStartView(ConfigData.getInstance().curLevel);
			}
		});
		next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setGameStartView(ConfigData.getInstance().curLevel+1);
			}
		});
		ConfigData.getInstance().status = 5;
		ConfigData.getInstance().curScore = score;
		ConfigData.getInstance().curStar = star;
		ConfigHandler.saveData();
	}
	public void setActivity(Activity activity){
		this.activity = activity;
	}
}